/**
 * @product: SOD
 * @copyright: FSAI-南征北战信息科技
 * @filename: com.sod.config.BaseEnumConverterFactory.java
 *
 * @link: Http://www.fastsai.com
 * @jdkv: Jdk 1.8
 */
package com.fsai.cms.config;

import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import com.fsai.cms.util.IBaseEnum;

/**
 * 枚举转换
 * 
 * @project: sod-web-admin
 *
 * @author: JaffeHe
 * @email: JaffeHe@foxmail.com
 * @date: 2020-06-08 10:43
 *
 * @ChangeLog<br/>
 * 				Developer Date Comment <br/>
 */
@SuppressWarnings("rawtypes")
public class BaseEnumConverterFactory implements ConverterFactory<String, IBaseEnum> {

	private static final Map<Class, Converter> converterMap = new WeakHashMap<>();

	@SuppressWarnings("unchecked")
	@Override
	public <T extends IBaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
		Converter result = converterMap.get(targetType);
		if (result == null) {
			result = new IntegerStrToEnum<T>(targetType);
			converterMap.put(targetType, result);
		}
		return result;
	}

	class IntegerStrToEnum<T extends IBaseEnum> implements Converter<String, T> {
		@SuppressWarnings("unused")
		private final Class<T> enumType;
		private Map<String, T> enumMap = new HashMap<>();

		public IntegerStrToEnum(Class<T> enumType) {
			this.enumType = enumType;
			T[] enums = enumType.getEnumConstants();
			for (T e : enums) {
				enumMap.put(e.getIndex() + "", e);
			}
		}

		@Override
		public T convert(String source) {
			T result = enumMap.get(source);
			if (result == null) {
				throw new IllegalArgumentException("No element matches " + source);
			}
			return result;
		}
	}

}
